package com.bodacn.keypoint;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.graphics.Rect;
import android.graphics.RectF;
import androidx.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/*专门用于绘制库位图*/
public class PlaceView extends View {
    public JSONArray placeJson,stateJson,totalJson,placeItemJson;

    public int imgWidth=1720,imgHeight=1020;
    public boolean AutoZoom=true;//自动缩放;
    public PlaceView(Context context) {
        super(context);
        InitView();
    }

    public PlaceView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        InitView();
    }

    public PlaceView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        InitView();
    }

    //判断是否为数字
    public static boolean isNumer(String str) {
        Pattern pattern = Pattern.compile("-?[0-9]+\\.?[0-9]+");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }
    //初始化;
    public void InitView() {
        try {
            placeJson=new JSONArray("[]");
            placeItemJson=new JSONArray("[]");
            stateJson=new JSONArray("[]");
            totalJson=new JSONArray("[]");
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Paint mPaint=new Paint();
        Bitmap bitmap=null;
        Canvas bitmapCanvas = null;
        if (bitmap == null) {
            bitmap =Bitmap.createBitmap(imgWidth, imgHeight, Bitmap.Config.ARGB_8888);
            bitmapCanvas = new Canvas(bitmap);
        }
        bitmapCanvas.drawColor(Color.TRANSPARENT,PorterDuff.Mode.CLEAR); //this line moved outside if
        //表示第一次;
        if (placeJson!=null) {
            for(int i=0;i<placeJson.length();i++) {
                try {
                    if (placeJson.optJSONObject(i).has("isHouse") == true)
                        drawOnCanvas(placeJson.getJSONObject(i),bitmapCanvas);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        } else
        {
            drawDefault(canvas);
        }
        //画状态图;
        if (stateJson!=null) {
            //更新状态图;
            for(int i=0;i<stateJson.length();i++) {
                try {
                    if (stateJson.optJSONObject(i).has("HouseDeName") == true)
                        setStateCanvas(stateJson.getJSONObject(i),bitmapCanvas);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
        //画汇总状态图;
        if (totalJson!=null) {
            //更新状态图;
            for(int i=0;i<totalJson.length();i++) {
                try {
                    if (totalJson.optJSONObject(i).has("isHouse") == true)
                        drawOnCanvas(totalJson.getJSONObject(i),bitmapCanvas);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
        mPaint.setColor(Color.WHITE);
        Rect src=new Rect(0,0,imgWidth,imgHeight);
        Rect trg=new Rect(0,0,getWidth(),getHeight());
        if (AutoZoom==true) canvas.drawBitmap(bitmap,src,trg,mPaint);
        else canvas.drawBitmap(bitmap,0,0,mPaint);
        //输出所有库位;set
        System.out.println(placeItemJson);
        mPaint.reset();
        bitmap.recycle();
    }

    //根据库位名称获取对象
    private JSONObject getItemObject(String HouseDeName){
        if (placeItemJson==null) return null;
        try {
            for (int i=0;i<placeItemJson.length();i++)
            {
                if (placeItemJson.optJSONObject(i).getString("HouseDeName").equals(HouseDeName)==true) return placeItemJson.optJSONObject(i);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }
    //根据库位设置颜色;
    private void setStateCanvas(JSONObject jsonObject, Canvas canvas) {
        int PosX=0,PosY=0,Right=100,Bottom=100,PenColor=Color.BLACK,TxtSize=20;
        String DrawType="Rect",PenType="Fill";
        JSONObject itemJson;
        String HouseDeName;
        //初始化笔
        Paint paint = new Paint();
        Paint paintFrame = new Paint();
        //设置画笔颜色
        paint.setColor(PenColor);
        paint.setAntiAlias(true);//抗锯齿；
        paint.setDither(true);//柔和线条;
        paint.setTextSize(TxtSize);
        paint.setTextAlign(Paint.Align.LEFT);
        //框线样式
        paintFrame.setColor(Color.LTGRAY);
        paintFrame.setAntiAlias(true);//抗锯齿；
        paintFrame.setDither(true);//柔和线条;
        paintFrame.setTextSize(TxtSize);
        paintFrame.setStyle(Paint.Style.STROKE);
        paintFrame.setTextAlign(Paint.Align.LEFT);
        try {
            HouseDeName=jsonObject.getString("HouseDeName");
            System.out.println("HouseDeName:"+HouseDeName);
            itemJson=getItemObject(HouseDeName);
            if (itemJson!=null) {
                System.out.println("itemJson!null:"+itemJson);
                if (jsonObject.has("PenColor") == true) {
                    PenColor = Color.GRAY;
                    if (jsonObject.getString("PenColor").equals("Black") == true)
                        PenColor = Color.BLACK;
                    if (jsonObject.getString("PenColor").equals("Blue") == true)
                        PenColor = Color.BLUE;
                    if (jsonObject.getString("PenColor").equals("Yellow") == true)
                        PenColor = Color.YELLOW;
                    if (jsonObject.getString("PenColor").equals("Red") == true)
                        PenColor = Color.RED;
                    if (jsonObject.getString("PenColor").equals("Green") == true)
                        PenColor = Color.GREEN;
                    if (jsonObject.getString("PenColor").equals("Gray") == true)
                        PenColor = Color.LTGRAY;
                    if (jsonObject.getString("PenColor").equals("White") == true)
                        PenColor = Color.WHITE;
                    paint.setColor(PenColor);
                }
                //更新状态;
                if (jsonObject.has("DrawType") == true) DrawType = jsonObject.getString("DrawType");
                if (jsonObject.has("PenType") == true) PenType = jsonObject.getString("PenType");
                //从库位明细里取相关位置
                if (itemJson.has("PosX") == true) PosX = itemJson.getInt("PosX");
                if (itemJson.has("PosY") == true) PosY = itemJson.getInt("PosY");
                if (itemJson.has("Right") == true) Right = itemJson.getInt("Right");
                if (itemJson.has("Bottom") == true) Bottom = itemJson.getInt("Bottom");
                if (DrawType.equals("Rect")==true||DrawType.equals("RectText")==true) {
                    // 第一种
                    RectF rectF = new RectF(PosX, PosY, Right, Bottom);
                    //填充;
                    if (PenType.equals("Fill") == true) {
                        paint.setStyle(Paint.Style.FILL_AND_STROKE);
                        canvas.drawRect(rectF, paint);//画矩形;
                        canvas.drawRect(rectF, paintFrame);//画矩形框;
                    } else {
                        canvas.drawRect(rectF, paintFrame);//画矩形;
                    }
                }

            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    //初始页面
    private void drawDefault(Canvas canvas) {
        //初始化笔
        Paint paint = new Paint();
        //设置画笔颜色
        paint.setColor(Color.GRAY);
        paint.setAntiAlias(true);//抗锯齿；
        paint.setDither(true);//柔和线条;
        paint.setTextSize(30);
        paint.setStyle(Paint.Style.STROKE);
        //画长框
        RectF rectF = new RectF(50, 50, 50+getWidth()/3, 50+getHeight()/3);
        canvas.drawRect(rectF, paint);//画矩形;
        //写文字;
        canvas.drawText("Width:"+String.valueOf(getWidth()), 50, 50, paint);
        Path path = new Path();
        path.setLastPoint(50,50);
        path.lineTo(50,50+getHeight());//定义字符路径
        canvas.drawTextOnPath("Height:"+String.valueOf(getHeight()), path, 0,0, paint);

    }

    private void drawOnCanvas(JSONObject jobject,Canvas canvas) {
        boolean isHouse=false;
        if (jobject==null) return;
        int rx=2;//圆角半径
        int PosX=0,PosY=0,IncX=0,IncY=0,ItemCount=1,Width=100,Height=100,PenColor=Color.BLACK,TxtSize=20,SerialStart=1;
        String PreFix="",NxtFix="",DrawType="Rect",DrawText="ABC",Direction="H",PenType="Fill",FormatStr="%02d";
        String tmpStr;
        try {
            if (jobject.has("isHouse") == true) isHouse = jobject.getBoolean("isHouse");
            if (jobject.has("PosX") == true) PosX = jobject.getInt("PosX");
            if (jobject.has("PosY") == true) PosY = jobject.getInt("PosY");
            if (jobject.has("PreFix") == true) PreFix = jobject.getString("PreFix");
            if (jobject.has("NxtFix") == true) NxtFix = jobject.getString("NxtFix");
            if (jobject.has("ItemCount") == true) ItemCount = jobject.getInt("ItemCount");
            if (jobject.has("Width") == true) Width = jobject.getInt("Width");
            if (jobject.has("Height") == true) Height = jobject.getInt("Height");
            if (jobject.has("Direction") == true) Direction = jobject.getString("Direction");
            if (jobject.has("DrawType") == true) DrawType = jobject.getString("DrawType");
            if (jobject.has("DrawText") == true) DrawText = jobject.getString("DrawText");
            if (jobject.has("TxtSize") == true) TxtSize = jobject.getInt("TxtSize");
            if (jobject.has("PenColor") == true) {
                PenColor=Color.GRAY;
                if (jobject.getString("PenColor").equals("Black")==true) PenColor =Color.BLACK;
                if (jobject.getString("PenColor").equals("Blue")==true) PenColor =Color.BLUE;
                if (jobject.getString("PenColor").equals("Yellow")==true) PenColor =Color.YELLOW;
                if (jobject.getString("PenColor").equals("Red")==true) PenColor =Color.RED;
                if (jobject.getString("PenColor").equals("Green")==true) PenColor =Color.GREEN;
                if (jobject.getString("PenColor").equals("Gray")==true) PenColor =Color.LTGRAY;
                if (jobject.getString("PenColor").equals("White")==true) PenColor =Color.WHITE;
            }
            if (jobject.has("PenType") == true) PenType = jobject.getString("PenType");
            if (jobject.has("SerialStart") == true) SerialStart = jobject.getInt("SerialStart");
            if (jobject.has("FormatStr") == true) FormatStr = jobject.getString("FormatStr");
            //初始化笔
            Paint paint = new Paint();
            Paint paintFrame = new Paint();
            Paint paintText = new Paint();
            //设置画笔颜色
            paint.setColor(PenColor);
            paint.setAntiAlias(true);//抗锯齿；
            paint.setDither(true);//柔和线条;
            paint.setTextSize(TxtSize);
            paint.setTextAlign(Paint.Align.LEFT);
            //框线样式
            paintFrame.setColor(Color.LTGRAY);
            paintFrame.setAntiAlias(true);//抗锯齿；
            paintFrame.setDither(true);//柔和线条;
            paintFrame.setTextSize(TxtSize);
            paintFrame.setStyle(Paint.Style.STROKE);
            paintFrame.setTextAlign(Paint.Align.LEFT);
            //文字样式;
            paintText.setColor(Color.BLACK);
            paintText.setAntiAlias(true);//抗锯齿；
            paintText.setDither(true);//柔和线条;
            paintText.setTextSize(TxtSize);
            paintText.setTextAlign(Paint.Align.LEFT);
            //根据Count进行循环画;
            for (int i=0;i<ItemCount;i++){
                if (Direction.equals("H")==true) IncX=i*Width;
                if (Direction.equals("V")==true) IncY=i*Height;
                if (DrawType.equals("Text")==true) {
                    //序列号与SerialStart配套使用;
                    if (DrawText.equals("SERIAL")==true)
                    {
                        tmpStr=String.valueOf(SerialStart+i);
                        canvas.drawText(tmpStr, PosX+IncX, PosY+IncY, paint);
                    }
                    else canvas.drawText(DrawText, PosX+IncX, PosY+IncY, paint);
                }
                if (DrawType.equals("Rect")==true||DrawType.equals("RectText")==true) {
                    // 第一种
                    RectF rectF = new RectF(PosX+IncX, PosY+IncY, PosX+IncX+Width, PosY+IncY+Height);
                    //填充;
                    if (PenType.equals("Fill")==true) {
                        paint.setStyle(Paint.Style.FILL_AND_STROKE);
                        canvas.drawRect(rectF, paint);//画矩形;
                        canvas.drawRect(rectF, paintFrame);//画矩形框;
                    }else {
                        canvas.drawRect(rectF, paintFrame);//画矩形;
                    }
                    //居中显示文字;
                    if (DrawType.equals("RectText")==true)
                    {
                        //写文字;
                        paintText.setColor(PenColor);
                        if (PenType.equals("Fill")==true) paintText.setColor(Color.BLACK);
                        paintText.setTextAlign(Paint.Align.CENTER);
                        paintText.setTextSize(TxtSize);
                        Paint.FontMetrics fontMetrics = paintText.getFontMetrics();
                        float top = fontMetrics.top;//为基线到字体上边框的距离,即上图中的top
                        float bottom = fontMetrics.bottom;//为基线到字体下边框的距离,即上图中的bottom
                        int baseLineY = (int) (rectF.centerY() - top/2 - bottom/2);//基线中间点的y轴计算公式
                        canvas.drawText(DrawText,rectF.centerX(),baseLineY,paintText);
                    }
                }
                //画进度条
                if (DrawType.equals("Progress")==true)
                {
                    // 第一种
                    RectF rectF = new RectF(PosX+IncX, PosY+IncY, PosX+IncX+Width, PosY+IncY+Height);
                    //填充;
                    float postion=0;
                    if (isNumer(DrawText)==true) postion= Float.valueOf(DrawText);
                    if (postion>100) postion=100;
                    if (postion<0) postion=0;
                    int proWidth=0,proHeight=0;
                    if (Direction.equals("H")==true)
                    {
                        proWidth=(int)(1.00*postion/100*Width);
                        proHeight=Height;
                    } else
                    {
                        proWidth=Width;
                        proHeight=(int)(1.00*postion/100*Height);
                    }
                    //System.out.println("proWidth:"+proWidth +"  proHeight:"+proHeight);
                    //画进度
                    RectF rectP=new RectF(PosX+IncX, PosY+IncY, PosX+IncX+proWidth, PosY+IncY+proHeight);
                    paint.setStyle(Paint.Style.FILL_AND_STROKE);
                    canvas.drawRect(rectP, paint);
                    //写文字;
                    paintText.setTextAlign(Paint.Align.CENTER);
                    paintText.setColor(Color.BLACK);
                    paintText.setTextSize(TxtSize);
                    Paint.FontMetrics fontMetrics = paintText.getFontMetrics();
                    float top = fontMetrics.top;//为基线到字体上边框的距离,即上图中的top
                    float bottom = fontMetrics.bottom;//为基线到字体下边框的距离,即上图中的bottom
                    int baseLineY = (int) (rectF.centerY() - top/2 - bottom/2);//基线中间点的y轴计算公式
                    canvas.drawText(DrawText+"%",rectF.centerX(),baseLineY,paintText);
                    //画框;
                    canvas.drawRect(rectF, paintFrame);
                }
                //System.out.println((PosX+IncX)+":"+(PosY+IncY)+"--"+DrawType);
                //暂存库位明细;
                if (isHouse==true) {
                    String HouseDeName=PreFix + String.format(FormatStr, SerialStart+i)+NxtFix;
                    if (getItemObject(HouseDeName)==null) {
                        JSONObject jsonItem = new JSONObject();
                        jsonItem.put("HouseDeName", HouseDeName);
                        jsonItem.put("PosX", PosX + IncX);
                        jsonItem.put("PosY", PosY + IncY);
                        jsonItem.put("Right", PosX + IncX + Width);
                        jsonItem.put("Bottom", PosY + IncY + Height);
                        jsonItem.put("DrawType", DrawType);
                        jsonItem.put("DrawText", DrawText);
                        jsonItem.put("PenType", PenType);
                        jsonItem.put("PenColor", PenColor);
                        placeItemJson.put(jsonItem);
                    }
                }

            }
            paint.reset();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}